import os

import yaml


class YamlUtil:
    def __init__(self):
        self.data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "data\\")

    def read_yaml_noparams(self):
        with open(self.data_path + "extract.yaml", mode='r', encoding="utf-8") as file:
            result = yaml.load(stream=file, Loader=yaml.FullLoader)
            return result

    def read_yaml(self, filedire, filename, title):
        with open(self.data_path + filedire + "\\" + filename, mode='r', encoding="utf-8") as file:
            result = yaml.load(stream=file, Loader=yaml.FullLoader)
            if title:
                return result[title]
            else:
                return result

    # 重新组装data_yaml文件
    def assemble_yaml(self, filedire, filename, title):
        result = self.read_yaml(filedire, filename, title)[0]
        new_yaml = []
        for case_infp_value in result["case_info"]:
            new_yaml.append({"requests_info": result["requests_info"], "case_info": case_infp_value})
        return new_yaml

    def write_yaml(self, data):
        with open(self.data_path + "extract.yaml", mode='a', encoding='utf-8') as file:
            old_data = self.read_yaml_noparams()
            if old_data:
                for key, value in old_data.items():
                    old_data[key] = value
                    self.clear_yaml(self.data_path + "extract.yaml")
                yaml.dump(data=old_data, stream=file, allow_unicode=True, sort_keys=False)
            else:
                yaml.dump(data=data, stream=file, allow_unicode=True, sort_keys=False)

    # 清空yaml文件
    def clear_yaml(self, path):
        with open(path, mode='w', encoding='utf-8') as file:
            file.truncate()


if __name__ == '__main__':
    YamlUtil().write_yaml({"a": 1})
